/*
 * @Author: 徐建辰
 * @Date: 2022-02-14 16:28:57
 * @LastEditTime: 2022-02-16 10:37:42
 * @LastEditors: 徐建辰
 * @Description: 用户信息hook
 */
import {ref, onMounted} from 'vue'
import {Dialog, Toast} from 'vant'
import {md5} from 'js-md5'
import router from '@/router'
import useUserStore from '@/store/user'
import {hasUser, antiShake} from '@/utils/utils'
import {USER} from '@/utils/constant'
import {setItem, getItem, removeAll} from '@/utils/local'
import {getUserInfo, logout} from '@/service/user'

export default function useUserInfo() {
  const userStore = useUserStore()
  console.log(hasUser())
  const userInfo = ref(hasUser() ? getItem(USER) : {})

  onMounted(() => {
    !hasUser() && getUser()
  })

  // 获取用户信息
  async function getUser() {
    const {data} = await getUserInfo()
    console.log(data);
    if (!data) return
    userInfo.value = data
    setItem(USER, data)
    userStore.getUserInfo()
  }
  // 用户修改信息
  function modifyUserInfo(introduceSign, nickName, password) {
    if (password.value) params.passwordMd5 = md5(password.value)
    antiShake(async () => {
      const {resultCode} = await editUserInfo({introduceSign, nickName})
      resultCode === 200 && Toast.success('修改成功')
    })
  }
  // 用户退出登录（放在pinia也未尝不可）
  function userLogout() {
    Dialog.confirm({
      title: '温馨提示！',
      message: '确定要退出登录吗？',
    }).then(async () => {
      Toast.loading('退出中...')
      const {resultCode, message} = await logout()
      if (resultCode !== 200) {
        Toast.fail('退出异常')
        Toast.clear()
        return
      }
      removeAll()
      router.replace({path: '/login'})
    })
  }

  return {userInfo, getUser, modifyUserInfo, userLogout}
}
